package org.example.quartz.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.Session;
import cn.hutool.db.ds.simple.SimpleDataSource;
import lombok.extern.slf4j.Slf4j;
import org.example.quartz.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(path = "/GSYY/ContactUnits")
public class ContactUnitsController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Value(value = "${spring.datasource.databaseType}")
    private String databaseType;

    @Value(value = "${spring.datasource.GSYY}")
    private String GSYY;

    @Value("${spring.datasource.url}")
    private String jdbcUrl;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;

    /**
     * 查询列表
     *
     * @param param
     * @return
     */
    @PostMapping("/getList")
    public Result getList(@RequestBody Map<String, Object> param) {
        try {
            String condition = "";
            // 拼接条件
            if (!ObjectUtils.isEmpty(param.get("contact_name"))) {
                condition += " and CONTACT_NAME LIKE  '%" + param.get("contact_name") + "%'";
            }
            if (!ObjectUtils.isEmpty(param.get("contact_code"))) {
                condition += " and CONTACT_CODE LIKE '%" + param.get("contact_code") + "%'";
            }
            if (!ObjectUtils.isEmpty(param.get("social_credit_code"))) {
                condition += " and SOCIAL_CREDIT_CODE LIKE '%" + param.get("social_credit_code") + "%'";
            }
            Integer total = jdbcTemplate.queryForObject("select count(*) from " + GSYY + ".GS_CONTACT_UNITS where DELETE_STATE =0 " + condition, Integer.class);
            if ("oracle".equals(databaseType)) {
                List<Map<String, Object>> mapList = jdbcTemplate.queryForList("select * from " + GSYY + ".GS_CONTACT_UNITS where DELETE_STATE =0 " + condition + "order by CREATED_TIME desc OFFSET ((" + Integer.parseInt(param.get("pageNum").toString()) + " - 1 ) *" + Integer.parseInt(param.get("pageSize").toString()) + ") rows fetch next " + Integer.parseInt(param.get("pageSize").toString()) + " rows only");
                return Result.success(mapList, total);
            } else if ("dm".equals(databaseType)) {
                String sql = "select * from (select t.*,ROWNUM rn from " + GSYY + ".GS_CONTACT_UNITS t where DELETE_STATE =0  " + condition + ") where rn between " + (Integer.parseInt(param.get("pageNum").toString()) - 1) * Integer.parseInt(param.get("pageSize").toString()) + " and " + (Integer.parseInt(param.get("pageNum").toString())) * Integer.parseInt(param.get("pageSize").toString());
                List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
                return Result.success(mapList, total);
            } else {
                List<Map<String, Object>> mapList = jdbcTemplate.queryForList("select * from " + GSYY + ".GS_CONTACT_UNITS where DELETE_STATE =0 " + condition + "limit " + Integer.parseInt(param.get("pageSize").toString()) + " OFFSET " + (Integer.parseInt(param.get("pageNum").toString()) - 1) * Integer.parseInt(param.get("pageSize").toString()));
                return Result.success(mapList, total);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 修改
     *
     * @param id
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestParam("id") Integer id) {
        try {
            String updateSql = "UPDATE " + GSYY + ".GS_CONTACT_UNITS \n" +
                    "SET  DELETE_STATE = '1'\n" +
                    "WHERE\n" +
                    "\tID = '" + id + "'";
            int update = jdbcTemplate.update(updateSql);
            String msg = "";
            if (update > 0) {
                msg = "删除成功";
                return Result.success(msg);
            } else {
                msg = "删除失败";
                return Result.fail(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 查询单个
     *
     * @param id
     * @return
     */
    @GetMapping("/getById")
    public Result getById(@RequestParam("id") Integer id) {
        try {
            return Result.success(jdbcTemplate.queryForList("select * from " + GSYY + ".GS_CONTACT_UNITS where ID = '" + id + "'"));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }


    /**
     * 修改
     *
     * @param param
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody Map<String, Object> param) {
        try {
            String updateSql = "UPDATE GS_CONTACT_UNITS \n" +
                    "SET CONTACT_NAME = '" + param.get("contact_name") + "',\n" +
                    "CONTACT_CODE = '" + param.get("contact_code") + "',\n" +
                    "SOCIAL_CREDIT_CODE = '" + param.get("social_credit_code") + "'\n" +
                    "WHERE\n" +
                    "\tID = '" + param.get("id") + "'";
            int update = jdbcTemplate.update(updateSql);
            String msg = "";
            if (update > 0) {
                msg = "修改成功";
                return Result.success(msg);
            } else {
                msg = "修改失败";
                return Result.fail(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 添加
     *
     * @param param
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody Map<String, Object> param) {
        DataSource ds = new SimpleDataSource(jdbcUrl, username, password);
        try (Session session = Session.create(ds)) {
            if ("oracle".equals(databaseType)) {
                Entity entity = Entity.create("GS_CONTACT_UNITS");
                entity.set("ID", String.valueOf(IdUtil.getSnowflakeNextId()).substring(11));
                for (Map.Entry<String, Object> stringObjectEntry : param.entrySet()) {
                    entity.set(stringObjectEntry.getKey(), stringObjectEntry.getValue());
                }
                session.insert(entity);
            } else if ("rdjc".equals(databaseType)) {
                String insertSql = "INSERT INTO " + GSYY + ".GS_CONTACT_UNITS (ID, CONTACT_NAME, CONTACT_CODE, SOCIAL_CREDIT_CODE )\n" +
                        "VALUES\n" +
                        "\t( " +
                        "'" + String.valueOf(IdUtil.getSnowflakeNextId()).substring(11) + "', " +
                        "'" + param.get("contact_name") + "', " +
                        "'" + param.get("contact_code") + "', " +
                        "'" + param.get("social_credit_code") + "' " +
                        ")";
                jdbcTemplate.update(insertSql);
            } else {
                String insertSql = "INSERT INTO " + GSYY + ".GS_CONTACT_UNITS (ID, CONTACT_NAME, CONTACT_CODE, SOCIAL_CREDIT_CODE)\n" +
                        "VALUES\n" +
                        "\t( " +
                        "'" + String.valueOf(IdUtil.getSnowflakeNextId()).substring(11) + "', " +
                        "'" + param.get("contact_name") + "', " +
                        "'" + param.get("contact_code") + "', " +
                        "'" + param.get("social_credit_code") + "' " +
                        ")";
                jdbcTemplate.update(insertSql);
            }
            return Result.success("新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

}